package it.yuzuojian.com.util;

import it.yuzuojian.com.pojo.ColumnVo;
import it.yuzuojian.com.pojo.TableVo;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.WordUtils;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.app.VelocityEngine;

import java.io.*;
import java.util.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class GenUtils {
    public  List<String> getTemplates() {
        List<String> templates = new ArrayList<String>();
        // FileInputStream(DataSourceUtil.buildDirectory+ File.separator+"classes"+File.separator+"generator.properties");
        File pathFile = new File(DataSourceUtil.resourcesDirectory+File.separator+"generator");
        File[] files = pathFile.listFiles(new FilenameFilter() {
            @Override
            public boolean accept(File dir, String name) {
                return "vm".equals((name.substring(name.lastIndexOf(".")+1, name.length())));
            }
        });
        if(files==null){
            return templates;
        }
        for (File file : files) {
            templates.add(file.getName());
        }
        return templates;
    }

    public static String columnToJava(String columnName) {
        //WordUtils.capitalizeFully(columnName, new char[]{'_'})
        //in_stock_pp ====>In_Stock_Pp  instockpp ===>Instockpp
        return WordUtils.capitalizeFully(columnName, new char[]{'_'}).replace("_", "");
    }

    /**
     * 获取配置信息
     */
    /*public static Configuration getConfig() throws ConfigurationException {
        return new PropertiesConfiguration("generator.properties");
    }*/

    public  void generatorCode(Map<String, String> table, List<Map<String, String>> columns, ZipOutputStream zip) throws ConfigurationException, IOException {
        //配置信息
        //Configuration config = getConfig();
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("generator.properties");
        Properties properties = new Properties();
        properties.load(inputStream);

        //表信息
        TableVo TableVo = new TableVo();
        TableVo.setTableName(table.get("tableName"));
        TableVo.setComments(table.get("tableComment"));
        //这里直接用表名作为java类名，有需要可以进行定制化
        String className = columnToJava(TableVo.getTableName());
        TableVo.setClassName(className);

        //StringUtils.uncapitalize将首字母大写的转为小写
        //INstock ==>iNstock
        TableVo.setClassName_(StringUtils.uncapitalize(className));
        //列信息
        List<ColumnVo> columsList = new ArrayList<>();
        for (Map<String, String> column : columns) {
            ColumnVo ColumnVo = new ColumnVo();
            ColumnVo.setColumnName(column.get("columnName"));
            ColumnVo.setDataType(column.get("dataType"));
            ColumnVo.setComments(column.get("columnComment"));
            ColumnVo.setExtra(column.get("extra"));

            //列名转换成Java属性名
            String attrName = columnToJava(ColumnVo.getColumnName());
            ColumnVo.setAttrName(attrName);
            ColumnVo.setAttrName_(StringUtils.uncapitalize(attrName));

            //列的数据类型，转换成Java类型
            String attrType = properties.getProperty(ColumnVo.getDataType(), "String");
            ColumnVo.setAttrType(attrType);

            //是否主键
            if ("PRI".equalsIgnoreCase(column.get("columnKey")) && TableVo.getPK() == null) {
                TableVo.setPK(ColumnVo);
            }

            columsList.add(ColumnVo);
        }
        TableVo.setColumns(columsList);

        //没主键，则第一个字段为主键
        if (TableVo.getPK() == null) {
            TableVo.setPK(TableVo.getColumns().get(0));
        }

        //设置velocity资源加载器
        Properties prop = new Properties();
        prop.put("file.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");//加载classpath目录下的vm文件
        Velocity.init(prop);

        //封装模板数据
        Map<String, Object> map = new HashMap<>(16);
        map.put("tableName", TableVo.getTableName());
        map.put("comments", TableVo.getComments());
        map.put("pk", TableVo.getPK());
        map.put("className", TableVo.getClassName());
        map.put("classname", TableVo.getClassName_());
        map.put("pathName", properties.getProperty("package").substring(properties.getProperty("package").lastIndexOf(".") + 1));
        map.put("columns", TableVo.getColumns());
        map.put("attrName_", TableVo.getClassName_());
        map.put("package", properties.getProperty("package"));
        map.put("author", properties.getProperty("author"));
        map.put("email", properties.getProperty("email"));
        //map.put("datetime", DateUtils.format(new Date(), new Locale("Cina")));
        VelocityContext context = new VelocityContext(map);

        //获取模板列表
        List<String> templates = getTemplates();
        for (String template : templates) {
            //渲染模板
            StringWriter sw = new StringWriter();
            Template tpl = Velocity.getTemplate(template, "UTF-8");
            tpl.merge(context, sw);
            //添加到zip
            try {
                zip.putNextEntry(new ZipEntry(getFileName(template, TableVo.getClassName_(), TableVo.getClassName(), properties.getProperty("package").substring(properties.getProperty("package").lastIndexOf(".") + 1))));
                IOUtils.write(sw.toString(), zip, "UTF-8");
                IOUtils.closeQuietly(sw);
                zip.closeEntry();

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public  void generatorCode(Map<String, String> table, List<Map<String, String>> columns) throws Exception {
        //配置信息
        //Configuration config = getConfig();
        InputStream inputStream = new FileInputStream(DataSourceUtil.resourcesDirectory+File.separator+"generator.properties");
        Properties properties = new Properties();
        properties.load(inputStream);

        //表信息
        TableVo TableVo = new TableVo();
        TableVo.setTableName(table.get("tableName"));
        TableVo.setComments(table.get("tableComment"));
        //这里直接用表名作为java类名，有需要可以进行定制化
        String className = columnToJava(TableVo.getTableName());
        TableVo.setClassName(className);

        //StringUtils.uncapitalize将首字母大写的转为小写
        //INstock ==>iNstock
        TableVo.setClassName_(StringUtils.uncapitalize(className));
        //列信息
        List<ColumnVo> columsList = new ArrayList<>();
        for (Map<String, String> column : columns) {
            ColumnVo ColumnVo = new ColumnVo();
            ColumnVo.setColumnName(column.get("columnName"));
            ColumnVo.setDataType(column.get("dataType"));
            ColumnVo.setComments(column.get("columnComment"));
            ColumnVo.setExtra(column.get("extra"));

            //列名转换成Java属性名
            String attrName = columnToJava(ColumnVo.getColumnName());
            ColumnVo.setAttrName(attrName);
            ColumnVo.setAttrName_(StringUtils.uncapitalize(attrName));

            //列的数据类型，转换成Java类型
            String attrType = properties.getProperty(ColumnVo.getDataType(), "String");
            ColumnVo.setAttrType(attrType);

            //是否主键
            if ("PRI".equalsIgnoreCase(column.get("columnKey")) && TableVo.getPK() == null) {
                TableVo.setPK(ColumnVo);
            }

            columsList.add(ColumnVo);
        }
        TableVo.setColumns(columsList);

        //没主键，则第一个字段为主键
        if (TableVo.getPK() == null) {
            TableVo.setPK(TableVo.getColumns().get(0));
        }

        //设置velocity资源加载器
        Properties prop = new Properties();
        //根据绝对路径加载 (vm文件置于硬盘某分区中，如：d:/template)
        prop.setProperty(VelocityEngine.FILE_RESOURCE_LOADER_PATH, DataSourceUtil.resourcesDirectory+ File.separator+"generator");//根据绝对路径加载 (vm文件置于硬盘某分区中，如：d:/template/test.vm)


        Velocity.init(prop);

        //封装模板数据
        Map<String, Object> map = new HashMap<>(16);
        map.put("tableName", TableVo.getTableName());
        map.put("comments", TableVo.getComments());
        map.put("PK", TableVo.getPK());
        map.put("className", TableVo.getClassName());
        map.put("classname", TableVo.getClassName_());
        map.put("pathName", properties.getProperty("package").substring(properties.getProperty("package").lastIndexOf(".") + 1));
        map.put("columns", TableVo.getColumns());
        //map.put("attrName_", TableVo.getClassName_());
        map.put("package", properties.getProperty("package"));
        map.put("author", properties.getProperty("author"));
        map.put("email", properties.getProperty("email"));
        //map.put("datetime", DateUtils.format(new Date(), Locale.CANADA));
        VelocityContext context = new VelocityContext(map);

        //获取模板列表
        List<String> templates = getTemplates();
        for (String template : templates) {
            //渲染模板
            File file = new File(getFileName(template, TableVo.getClassName_(), TableVo.getClassName(), properties.getProperty("package")));
            if(!file.exists()){//多级目录不存在filterWriter会报错
                file.getParentFile().mkdirs();
            }
            BufferedWriter writer = new BufferedWriter(new FileWriter(file,false));
            Template tpl = Velocity.getTemplate(template, "UTF-8");
            tpl.merge(context, writer);
            writer.flush();
            writer.close();

        }
    }

    /**
     * 获取文件名
     */
    public  String getFileName(String template, String classname, String className, String packageName) {
        String packagePath = DataSourceUtil.sourceDirectory + File.separator;
        //String modulesname=config.getString("packageName");
        if (StringUtils.isNotBlank(packageName)) {
            packagePath += packageName.replace(".", File.separator) + File.separator;
        }

        if (template.contains("domain.java.vm")) {
            return packagePath + "domain" + File.separator + className + "Vo.java";
        }

        if (template.contains("pojo.java.vm")) {
            return packagePath + "pojo" + File.separator + className + "Vo.java";
        }

        if (template.contains("mapper.java.vm")) {
            return packagePath + "mapper" + File.separator + className + "Mapper.java";
        }

//		if(template.contains("Mapper.java.vm")){
//			return packagePath + "dao" + File.separator + className + "Mapper.java";
//		}

        if (template.contains("service.java.vm")) {
            return packagePath + "service" + File.separator + className + "Service.java";
        }

        if (template.contains("serviceImpl.java.vm")) {
            return packagePath + "service" + File.separator + "impl" + File.separator + className + "ServiceImpl.java";
        }

        if (template.contains("controller.java.vm")) {
            return packagePath + "controller" + File.separator + className + "Controller.java";
        }

        if (template.contains("mapper.xml.vm")) {
           // return "resources" + File.separator + "mapper" + File.separator + className + "Mapper.xml";
            return DataSourceUtil.resourcesDirectory+File.separator+"mapper"+File.separator+ className + "Mapper.xml";
        }

        if (template.contains("list.html.vm")) {
            return "main" + File.separator + "resources" + File.separator + "templates" + File.separator
                    + packageName + File.separator + classname + File.separator + classname + ".html";
            //				+ "modules" + File.separator + "generator" + File.separator + className.toLowerCase() + ".html";
        }
        if (template.contains("add.html.vm")) {
            return "main" + File.separator + "resources" + File.separator + "templates" + File.separator
                    + packageName + File.separator + classname + File.separator + "add.html";
        }
        if (template.contains("edit.html.vm")) {
            return "main" + File.separator + "resources" + File.separator + "templates" + File.separator
                    + packageName + File.separator + classname + File.separator + "edit.html";
        }

        if (template.contains("list.js.vm")) {
            return "main" + File.separator + "resources" + File.separator + "static" + File.separator + "js" + File.separator
                    + "appjs" + File.separator + packageName + File.separator + classname + File.separator + classname + ".js";
            //		+ "modules" + File.separator + "generator" + File.separator + className.toLowerCase() + ".js";
        }
        if (template.contains("add.js.vm")) {
            return "main" + File.separator + "resources" + File.separator + "static" + File.separator + "js" + File.separator
                    + "appjs" + File.separator + packageName + File.separator + classname + File.separator + "add.js";
        }
        if (template.contains("edit.js.vm")) {
            return "main" + File.separator + "resources" + File.separator + "static" + File.separator + "js" + File.separator
                    + "appjs" + File.separator + packageName + File.separator + classname + File.separator + "edit.js";
        }

//		if(template.contains("menu.sql.vm")){
//			return className.toLowerCase() + "_menu.sql";
//		}

        return null;
    }

}
